package com.bckj.freshnow.payment.pay.wxpay;

import cn.hutool.extra.spring.SpringUtil;
import com.bckj.freshnow.payment.entity.PayConfig;
import com.bckj.freshnow.payment.entity.PayMerchantConfig;
import com.bckj.freshnow.payment.pay.PaymentConfig;
import com.bckj.freshnow.payment.repo.PayConfigRepository;
import com.bckj.freshnow.payment.repo.PayMerchantConfigRepository;
import com.wechat.pay.java.core.Config;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class WxpayConfigProvider {

    private static final Map<String, Config> CONFIG_MAP = new ConcurrentHashMap<>();
    private static final Map<String, PaymentConfig> PAY_CONFIG_MAP = new ConcurrentHashMap<>();

    public static PaymentConfig get(String appId) {
        return PAY_CONFIG_MAP.computeIfAbsent(appId, key -> {
            PayConfig payConfig = SpringUtil.getBean(PayConfigRepository.class).getByAppId(key);
            if (payConfig != null) {
                PayMerchantConfig payMerchantConfig = payConfig.getPayMerchantConfig();
                if (payMerchantConfig != null) {
                    CONFIG_MAP.computeIfAbsent(payMerchantConfig.getOutMerchantId(), key1 -> buildConfig(payMerchantConfig));
                }
            }
            return null;
        });
    }
    public static Config getConfigByOutMerchantId(String outMerchantId) {
        return CONFIG_MAP.computeIfAbsent(outMerchantId, key1 -> {
            PayMerchantConfig payMerchantConfig = SpringUtil.getBean(PayMerchantConfigRepository.class).getByOutMerchantId(outMerchantId);
            if (payMerchantConfig != null) {
                return buildConfig(payMerchantConfig);
            }
            return null;
        });
    }

    private static Config buildConfig(PayMerchantConfig payMerchantConfig) {
        // 使用自动更新平台证书的RSA配置
        // 建议将 config 作为单例或全局静态对象，避免重复的下载浪费系统资源
        Config config =
                new RSAAutoCertificateConfig.Builder()
                        .merchantId(payMerchantConfig.getOutMerchantId())
                        .privateKey(payMerchantConfig.getPrivateKey())
                        .merchantSerialNumber(payMerchantConfig.getMerchantSerialNumber())
                        .apiV3Key(payMerchantConfig.getApiKey())
                        .build();
        log.info("Build WechatPay Config:{}", config);
        return config;
    }
}
